import { login, getUserInfo, getUserDetailById } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
const state = {
  token: getToken() || '',
  UserInfo: {}
}
const mutations = {
  setToken(state, data) {
    setToken(data)
    state.token = data
  },
  removeToken(state) {
    state.token = ''
    removeToken()
  },
  setUserInfo(state, data) {
    state.UserInfo = { ...data }
  },
  removeUserInfo(state) {
    state.UserInfo = {}
  }
}
const actions = {
  async login(store, data) {
    const res = await login(data)
    store.commit('setToken', res)
    // a.现在的时间戳 Data.now() 1970年1月1号一直数到现在的毫秒
    // b.时间戳的理解，定义一个时间1970年，来判定我们某一时刻的时间戳
    // c.登录的时候，将登陆时间保存在本地存储里面
    // d.注入token是在请求拦截器request内部-先做判定，再注入token
    localStorage.setItem('loginTime', Date.now())
  },
  async getUserInfo(store) {
    const res = await getUserInfo()
    console.log(res)
    const detail = await getUserDetailById(res.userId)
    store.commit('setUserInfo', {
      ...res,
      ...detail,
      staffPhoto: null
    })
  },
  logout(store) {
    store.commit('removeToken')
    store.commit('removeUserInfo')
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

